package com.jdk.learn.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by baiguantao on 2017/10/10.
 */
public class NioDemo {


    /**
     * nio 学习示例
     * https://www.ibm.com/developerworks/cn/java/j-lo-javaio/
     * @throws IOException
     */
    public  void selector() throws IOException {
        //字节缓存区
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        //打开selector
        Selector selector=Selector.open();
        ServerSocketChannel ssc=ServerSocketChannel.open();

        ssc.configureBlocking(false);//设置成非阻塞
        ssc.bind(new InetSocketAddress(9090));//绑定端口

        //注册接受链接事件
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            Set set=selector.selectedKeys();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()){
                SelectionKey key= (SelectionKey) iterator.next();
                if ((key.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel accept = channel.accept();
                    accept.configureBlocking(false);
                    accept.register(selector,SelectionKey.OP_READ);
                    iterator.remove();
                } else if ((key.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ) {
                    SocketChannel read = (SocketChannel) key.channel();
                    while (true){
                        buffer.clear();
                        int i=read.read(buffer);
                        if (i<=0) {
                            break;
                        }
                        buffer.flip();//压入数据  并将postion置为0
                    }
                    iterator.remove();
                }

            }
        }


    }
}
